package com.qbb.client.security;

import java.io.UnsupportedEncodingException;

/**
 * 类说明
 * 
 * @author chenhuaiao
 * @version V1.0 创建时间：Mar 18, 2015 6:10:17 PM
 */
public class SecurityUtil {
	public static String kek = "F729B631CB1F4A01A44F10D64FF2FBC4";

	/**
	 * 
	 * @param finalStr
	 * @param keyStr
	 * @param type
	 * @return
	 */
	public static String getSecurityStr(String finalStr, String keyStr, int type) {
		if (type == 0) {
			String hexString = toHexString(finalStr);
			String descurityStr = DESDigest.DES_3_Data(hexString, keyStr, 0);
			return descurityStr;
		}
		if (type == 1) {
			String escurityStr = DESDigest.DES_3_Data(finalStr, keyStr, 1);
			String hexString = toStringHex(escurityStr);
			return hexString;
		}
		return null;
	}

	/**
	 * 
	 * @param requestUrl
	 * @return
	 */
	public static String getFinalStr(String requestUrl) {
		String appendRequestUrl = "|" + requestUrl;
		int appendRequestLen = appendRequestUrl.length();
		int appendReqStrLen = String.valueOf(appendRequestLen).length();

		int finalAppendLen = appendRequestLen
				+ String.valueOf(appendRequestLen).length();
		int finalAppendStrLen = String.valueOf(finalAppendLen).length();

		int finalLen = finalAppendLen;

		if (finalAppendStrLen > appendReqStrLen) {
			finalLen += 1;
		}

		String finalStr = finalLen + appendRequestUrl;

		return finalStr;
	}

	/**
	 * 将字符串格式化成十六进制字符串表示
	 * 
	 * @param value
	 * @return
	 */
	public static String toHexString(String value) {
		if (value == null || value.trim().length() == 0) {
			return "";
		}
		byte[] bs = null;
		try {
			bs = value.getBytes("gbk");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < bs.length; i++) {
			int v = bs[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString().toUpperCase();
	}

	/**
	 * 十六进制数据转成字符串
	 * 
	 * @param s
	 * @return
	 */
	public static String toStringHex(String s) {
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(
						s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "gbk");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s;
	}

}
